/*
 *  DispatcherThread.c
 *  ClientDispatch
 *
 *  Created by Andrey on 14/10/2008.
 *  Copyright 2008 ИУ7-2003. All rights reserved.
 *
 */

#include <pthread.h>

#include "DispatcherThread.h"
#include "ClientQueue.h"
#include "WorkerThreadPool.h"

pthread_t _dispatcherThread;
CDClientInfoPtr _clientAssignment[WORKER_THREAD_POOL_CAPACITY];

static void* DispatchRoutine(void* arguments)
{
	InitWorkerThreadPool(NULL);
	
	while (1)
	{
		CDClientInfoPtr clientInfo = GetFirstClientInQueue();
		
		if (clientInfo != NULL)
		{
			int freeThreadId = GetUnoccupiedThreadIdFromPool();
			if (freeThreadId != -1)
			{
				_clientAssignment[freeThreadId] = clientInfo;
				AwakeWorkerThread(freeThreadId);
			}
		}
	}
	
	PurgeWorkerThreadPool();
}

CDClientInfoPtr GetClientAssignmentForWorkerThread(int workerThreadId)
{
	return _clientAssignment[workerThreadId];
}

void StartDispatcherThread()
{
	pthread_create(&_dispatcherThread, NULL, DispatchRoutine, NULL);
}